<template>
  <div>
    <el-dialog
      v-model="isShow"
      :title="$demoi18n('panel.thresholdSetting.dialogTitle')"
      width="400px"
      top="8.4vh"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      :class="`${customClass} ${visualThemeClassName} threshold-setting-shape-dialog ${xvueNameSpace}`"
    >
      <div class="threshold-setting-main">
        <PanelLabelOverflowTooltip ref="panelLabelOverflowTooltip" />
        <el-form
          ref="form"
          v-panel-label-overflow-tooltip="getPanelLabelOverflowTooltip()"
          class="form"
          label-position="right"
          :model="thresholdForm"
          :rules="rules"
          label-width="100px"
        >
          <p :class="`shapeTip ${xvueTheme}`">{{ $demoi18n('label.thresholdSetting.shape.tip') }}</p>
          <VsFormItem :label="$demoi18n('word.threshold')" class="el-form-shape-switch">
            <el-switch v-model="thresholdForm.isShapeThreshold"></el-switch>
          </VsFormItem>
          <VsFormItem
            v-if="thresholdForm.isShapeThreshold"
            :label="$demoi18n('word.valueType')"
            prop="thresholdDataType"
          >
            <el-select
              v-model="dataType"
              :class="'panel-data-select-' + xvueTheme"
              :popper-class="'select-poper-' + xvueTheme"
              :placeholder="$demoi18n('word.plsSelect')"
              size="default"
              @change="handleDataTypeChange"
            >
              <el-option
                v-for="item in dataTypeOptions"
                :key="item.value"
                class="count-option"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </VsFormItem>
          <VsFormItem
            v-if="thresholdForm.isShapeThreshold"
            :label="$demoi18n('word.thresholdLegend')"
          >
            <el-switch v-model="thresholdForm.isThreshodLegendShow"></el-switch>
          </VsFormItem>
          <VsFormItem
            v-if="thresholdForm.isShapeThreshold && thresholdForm.isThreshodLegendShow && form.thresholdDisplay"
            :label="$demoi18n('word.thresholdDisplay')"
          >
            <el-radio-group
              v-model="form.thresholdDisplay"
              class="icon-radio-group"
            >
              <el-radio
                v-for="(item, index) in threDisplayStyle"
                :key="index"
                :label="item.value"
                border
              >
                <img
                  :src="item.img"
                  :alt="item.key"
                />
              </el-radio>
            </el-radio-group>
          </VsFormItem>

          <div
            v-if="thresholdForm.isShapeThreshold"
            class="config-table"
          >
            <el-button
              class="btn-sure button-sure"
              size="default"
              icon="CirclePlus"
              @click.stop="addNewRow(thresholdTemp, thresholdItem)"
            >{{ $demoi18n('btn.add') }}</el-button>
            <el-tooltip
              v-if="dataType === 'number'"
              class="item"
              :effect="xvueTheme"
              :content="$demoi18n('word.shapeSetting.helptip')"
              placement="top-start"
            >
              <el-button
                :link="true"
                type="primary"
                :style="{ marginLeft: '5px' }"
              >
                <el-icon><InfoFilled /></el-icon>
              </el-button>
            </el-tooltip>
            <el-table
              class="config-panel-table mapping-table"
              :data="thresholdForm.thresholdData"
              :row-style="{ height: '25px' }"
              :header-row-style="{ height: '25px' }"
              max-height="500"
              :header-cell-style="{ lineHeight: '15px' }"
            >
              <el-table-column
                type="index"
                width="50"
                :label="$demoi18n('panel.th.number')"
              > </el-table-column>
              <el-table-column
                v-if="dataType === 'number'"
                :label="$demoi18n('panel.label.thresholdRange')"
                :min-width="isIcon ? 135 : 170"
              >
                <template #header="{column}">
                  <el-tooltip
                    placement="top"
                    :content="`${column.label} eg: a <= x < b`"
                    :effect="xvueTheme"
                  >
                    <div>
                      <span>{{ column.label }}</span>
                      <span
                        :style="{
                          marginLeft: '5px',
                          fontSize: '12px',
                          color: xvueTheme === 'dark'? '#fff': '#999',
                        }"
                      >eg: a &lt;= x &lt; b</span>
                    </div>
                  </el-tooltip>
                </template>
                <template #default="scope">
                  <div class="threshold-column">
                    <VsFormItem :prop="`thresholdData[${scope.$index}].min`">
                      <el-input-number
                        v-model="scope.row.min"
                        :placeholder="$demoi18n('panel.thresholdSetting.leftVal')"
                        size="default"
                        :style="{ width: '100%' }"
                        :controls="false"
                      ></el-input-number>
                    </VsFormItem>
                    <span :style="{ margin: '0 3px' }">-</span>
                    <VsFormItem :prop="`thresholdData[${scope.$index}].max`">
                      <el-input-number
                        v-model="scope.row.max"
                        :placeholder="$demoi18n('panel.thresholdSetting.rightVal')"
                        size="default"
                        :style="{ width: '100%' }"
                        :controls="false"
                      ></el-input-number>
                    </VsFormItem>
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                v-if="dataType === 'string'"
                :label="$demoi18n('panel.thresholdSetting.parameterCharacter')"
                :min-width="isIcon ? 125 : 170"
              >
                <template #header="{column}">
                  <ThCell :label="column.label" />
                </template>
                <template #default="scope">
                  <VsFormItem
                    :prop="`thresholdData[${scope.$index}].text`"
                    :rules="
                      generateRules({
                        required: false,
                        label: $demoi18n('panel.thresholdSetting.parameterCharacter'),
                      })
                    "
                  >
                    <ValueInputer
                      v-model:value="scope.row.text"
                      :enum-values="nameList"
                    />
                  </VsFormItem>
                </template>
              </el-table-column>

              <el-table-column
                prop="color"
                :label="$demoi18n('echart.th.color')"
                :min-width="55"
              >
                <template #header="{column}">
                  <ThCell :label="column.label" />
                </template>
                <template #default="scope">
                  <el-color-picker
                    v-model="scope.row.color"
                    :popper-class="'vis-color-picker-panel-' + xvueTheme"
                    color-format="hex"
                    :predefine="predefineColors"
                    size="default"
                    :style="{ 'vertical-align': 'bottom' }"
                    append-to=".threshold-setting-shape-dialog"
                  ></el-color-picker>
                </template>
              </el-table-column>
              <el-table-column
                :label="$demoi18n('word.operation')"
                :min-width="30"
              >
                <template #header="{column}">
                  <ThCell :label="column.label" />
                </template>
                <template #default="scope">
                  <el-button
                    icon="Delete"
                    :link="true"
                    type="primary"
                    @click.stop="deleteCurRow(scope.row)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <VsFormItem
            v-if="thresholdForm.isShapeThreshold"
            :label="$demoi18n('word.outOfThresholdColor')"
            label-width="140px"
          >
            <el-color-picker
              v-model="thresholdForm.outOfThresholdColor"
              :popper-class="'vis-color-picker-panel-' + xvueTheme"
              color-format="hex"
              :predefine="outPredefineColors"
              size="default"
              :style="{ 'vertical-align': 'middle' }"
              append-to=".threshold-setting-shape-dialog"
            ></el-color-picker>
          </VsFormItem>
          <VsFormItem
            v-if="thresholdForm.thresholdLegendPosition && thresholdForm.isShapeThreshold"
            :label="$demoi18n('word.thresholdLegendPosition')"
          >
            <el-select
              v-model="thresholdForm.thresholdLegendPosition"
              :class="'panel-data-select-' + xvueTheme"
              :popper-class="'select-poper-' + xvueTheme"
              :placeholder="$demoi18n('word.plsSelect')"
              size="default"
            >
              <el-option
                v-for="item in legendPositionOptions"
                :key="item.value"
                class="count-option"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </VsFormItem>
        </el-form>
        <div class="action-button-group">
          <el-button
            class="button-sure"
            size="default"
            type="primary"
            @click="handleSave()"
          >{{
            $demoi18n('btn.confirm')
          }}</el-button>
          <el-button
            class="button-cancel"
            size="default"
            @click="cancel()"
          >{{ $demoi18n('btn.close') }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang='jsx'>
import PanelLabelOverflowTooltip from '@/components/common/overflow-tooltip/overflow-tooltip.vue';
import ThCell from '@/components/common/th-cell/th-cell.vue';
import ValueInputer from '@/components/common/value-inputer/value-inputer.vue';
import imgUploadBase from '@/mixin/img-upload-base';
import { generateRules, genRequireRule } from '@/utils/rules';

const requireImg = url => {
  const modules = import.meta.glob('./icon/*.png', { eager: true, import: 'default' });
  return modules[url];
};

export default {
  name: 'ThresholdSetting',
  components: { ValueInputer, PanelLabelOverflowTooltip, ThCell },
  mixins: [imgUploadBase],
  props: ['form', 'isIcon', 'config', 'activeColorRadio', 'activeColorSwitch', 'nameList'],
  emits: ['save'],
  data() {
    return {
      xvueNameSpace: process.env.xvueNameSpace, // 给挂载在body下的元素加上主类名
      xvueTheme: window._adoPremise.uc.theme,
      customClass: `threshold-setting-dialog threshold-setting-dialog-${window._adoPremise.uc.theme || 'light'}`,
      isShow: false,
      thresholdForm: {},
      thresholdItem: {
        min: undefined,
        max: undefined,
        text: '',
        color: '#ff5071',
      },
      thresholdTemp: {},
      dataType: 'number',
      dataTypeOptions: [
        {
          value: 'number',
          label: this.$demoi18n('word.numValue'),
        },
        {
          value: 'string',
          label: this.$demoi18n('word.string'),
        },
      ],
      legendPositionOptions: [
        {
          value: 'topRight',
          label: this.$demoi18n('panel.lab.topRight'),
        },
        {
          value: 'topLeft',
          label: this.$demoi18n('panel.lab.topLeft'),
        },
        {
          value: 'bottomRight',
          label: this.$demoi18n('panel.lab.bottomRight'),
        },
        {
          value: 'bottomLeft',
          label: this.$demoi18n('panel.lab.bottomLeft'),
        },
        {
          value: 'rightTop',
          label: this.$demoi18n('panel.lab.rightTop'),
        },
        {
          value: 'leftTop',
          label: this.$demoi18n('panel.lab.leftTop'),
        },
        {
          value: 'rightBottom',
          label: this.$demoi18n('panel.lab.rightBottom'),
        },
        {
          value: 'leftBottom',
          label: this.$demoi18n('panel.lab.leftBottom'),
        },
      ],
      threDisplayStyle: [
        {
          key: 'horiztText',
          img: '',
          img: requireImg(`./icon/1${window._adoPremise.uc.theme}.png`),
          value: 'horiztText',
        },
        {
          key: 'vertical',
          img: '',
          img: requireImg(`./icon/2${window._adoPremise.uc.theme}.png`),
          value: 'vertical',
        },
        {
          key: 'horiztNoText',
          img: '',
          img: requireImg(`./icon/3${window._adoPremise.uc.theme}.png`),
          value: 'horiztNoText',
        },
      ],
      stringDataOption: [],
      predefineColors: ['#ff5071'],
      outPredefineColors: ['#A7A8C7'],
      rules: {
        thresholdDataType: genRequireRule({
          label: this.$demoi18n('word.valueType'),
        }),
      },
    };
  },
  computed: {
    thisComp() {
      return this;
    },
  },
  watch: {},
  methods: {
    genRequireRule,
    generateRules,
    getPanelLabelOverflowTooltip() {
      return {
        parentComp: this,
      };
    },
    openDialog() {
      const {
        isShapeThreshold,
        shapeThreshold,
        thresholdDataType,
        isThreshodLegendShow,
        thresholdLegendPosition,
        outOfThresholdColor,
      } = this.form;
      const thresholdData = JSON.parse(JSON.stringify(shapeThreshold));
      this.dataType = thresholdDataType;
      this.thresholdForm = {
        isShapeThreshold,
        thresholdData,
        thresholdDataType: this.dataType,
        isThreshodLegendShow,
        thresholdLegendPosition,
        outOfThresholdColor,
      };
      this.isShow = true;
    },
    cancel() {
      this.isShow = false;
    },
    handleDataTypeChange(val) {
      this.thresholdForm.thresholdDataType = this.dataType;
    },
    addNewRow(temp, item) {
      const _temp = JSON.parse(JSON.stringify(item));
      this.thresholdForm.thresholdData.push(_temp);
    },
    deleteCurRow(item) {
      const index = this.thresholdForm.thresholdData.indexOf(item);
      this.thresholdForm.thresholdData.splice(index, 1);
    },

    checkThreshold() {
      let errorText = '';
      if (this.dataType === 'string') {
        const textArray = this.thresholdForm.thresholdData.map(data => data.text).filter(text => text !== '');
        const textSet = new Set(textArray);
        textSet.delete('');
        if (textSet.size < textArray.length) {
          errorText = this.$demoi18n('message.duplicateStringThreshold');
          this.emitToPanel(errorText);
          return false;
        }
      } else {
        const rangeArray = [];
        this.thresholdForm.thresholdData.forEach((item, index) => {
          let { min } = item;
          let { max } = item;
          if (min === null) {
            min = Number.MIN_SAFE_INTEGER;
          }
          if (max === null) {
            max = Number.MAX_SAFE_INTEGER;
          }
          rangeArray[index] = [min, max];
        });
        for (let i = 0; i < rangeArray.length; i++) {
          if (rangeArray[i][0] >= rangeArray[i][1]) {
            errorText = this.$demoi18n('message.wrongThresholdRange');
            this.emitToPanel(errorText);
            return false;
          }
        }
        for (let i = 0; i < rangeArray.length; i++) {
          for (let j = 0; j < i; j++) {
            if (
              (rangeArray[i][0] >= rangeArray[j][0] && rangeArray[i][0] < rangeArray[j][1]) ||
              (rangeArray[i][1] > rangeArray[j][0] && rangeArray[i][1] < rangeArray[j][1])
            ) {
              errorText = this.$demoi18n('message.thresholdRepetition');
              this.emitToPanel(errorText);
              return false;
            }
          }
        }
      }
      return true;
    },

    emitToPanel(error) {
      this.$message.error(error);
    },

    handleSave() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return;
        }
        if (!this.checkThreshold()) {
          return;
        }
        this.$emit('save', this.thresholdForm);
        this.cancel();
      });
    },
  },
};
</script>

<style lang="less">
@import '../../../common/color-picker-panel.less';
</style>
<style lang="less" scoped>
// .threshold-setting-dialog {
  .threshold-setting-main {
    .form {
      width: 100%;
      .shapeTip {
        margin: 0 30px;
        font-size: 12px;
      }
      .shapeTip.dark {
        color: #95c0dc;
      }
      .shapeTip.light {
        color: #606266;
      }
      .el-form-shape-switch {
        align-items: center;
      }
      :deep(.el-form-item) {
        margin-bottom: 0;
        .el-form-item__label {
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
      }
      .icon-radio-group {
        :deep(.el-radio) {
          padding: 0;
          border-radius: 0;
          height: auto;
          margin-right: 10px;
          .el-radio__input {
            display: none;
          }
          .el-radio__label {
            padding-left: 0;
            display: flex;
            img {
              height: 55px;
              width: 60px;
            }
          }
        }
      }
      .config-table {
        :deep(.el-table) {
          .el-form-item__error {
            top: 100%;
            padding-top: 0;
          }
          .is-error {
            margin-bottom: 15px;
          }
          .cell {
            padding: 0 3px !important;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            .threshold-column {
              display: flex;
              align-items: center;
            }
            .el-input__inner {
              padding: 0 5px !important;
            }
          }
          td,
          th {
            padding: 5px 0 !important;
          }
          th div {
            display: inline;
            line-height: 15px;
          }
          .el-table__row > td {
            border: none;
          }
        }
        :deep(.el-form-item__content) {
          margin-left: 0 !important;
        }
      }
    }
  }

  .action-button-group {
    text-align: right;
    padding-top: 20px;
    .button-sure {
      padding: 9px 35px;
      border-radius: 0;
    }
    .button-cancel {
      padding: 9px 35px;
      border-radius: 0;
    }
  }
// }
.icon-library-dialog-dark {
  .icon-library-main {
    background-color: #071f30;
  }
  .action-button-group {
    .button-sure {
      background-color: #0eb4c2;
      color: #fff;
    }
    .button-cancel {
      background-color: #064559;
      border-color: #064559;

      color: #fff;
    }
  }
}
</style>

<style lang="less">
@font_color_dark: #98cae6;
@borderColor_dark: #116584;
@textColor_dark: #ffffff;
@bgColor_dark: #000c17;
@font_color_active_dark: #00f0ff;
@background_color_dark: #071f30;
.threshold-setting-dialog-dark {
  .el-dialog__header {
    background: #183c5a;
    .el-dialog__title {
      color: #fff;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #fff;
      }
    }
  }

  .el-dialog__body {
    background: #0e2b40;

    .el-form-item__label {
      color: @font_color_dark;
    }

    .el-input {
      .el-input__inner {
        border-color: @borderColor_dark;
        color: @textColor_dark;
        background-color: @bgColor_dark;
      }

      .el-input__icon {
        color: @borderColor_dark;
      }
    }

    .el-radio-group {
      .el-radio {
        color: @textColor_dark;

        .el-radio__input {
          .el-radio__inner {
            border-color: @font_color_active_dark;
            background-color: unset;
          }
        }

        .is-checked {
          .el-radio__inner {
            &::after {
              background-color: @font_color_active_dark;
            }
          }
        }

        .el-radio__label {
          color: #fff;
        }
      }
      .is-checked {
        .el-radio__label {
          color: #00f0ff;
        }
      }
    }

    .el-switch__core {
      background-color: #064559;
      border-color: #064559;
    }

    .el-switch.is-checked {
      .el-switch__core {
        background-color: #0eb4c2;
        border-color: #0eb4c2;
      }
    }

    .el-color-picker {
      .el-color-picker__trigger {
        border-color: @borderColor_dark;
      }
    }
    // 表格
    .config-panel-table {
      color: @font_color_dark;
      background-color: @background_color_dark;

      &::before {
        background-color: @background_color_dark;
      }

      .cell {
        padding: 0 3px !important;
      }
      td,
      th {
        padding: 5px 0 !important;
      }

      .el-table__header {
        th {
          background-color: #122b40 !important;
          border-color: #122b40;
          color: @font_color_dark;
        }
      }

      .el-table__body {
        tr {
          td {
            background-color: @background_color_dark;
            border-color: @background_color_dark;

            .icon-library-open {
              background-color: unset;
              border-color: #0eb4c2;
            }
          }
        }
      }

      .el-table__empty-block {
        background-color: #093758;

        .el-table__empty-text {
          color: @font_color_active_dark;
        }
      }
    }

    .button-sure {
      background-color: #0eb4c2;
      border-color: #0eb4c2;
      color: #fff;

      .el-icon-circle-plus {
        color: #fff;
      }
    }

    .button-cancel {
      background-color: #064559;
      border-color: #064559;
      color: #fff;

      .el-icon-circle-plus {
        color: #fff;
      }
    }
  }
}
</style>
